package com.encrypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class EncryptedString extends Activity {

	TextView tstring;
	TextView outString;
	String L;
	String Y;
	public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
	public static final String KEY_PRIVATE = "KEY_PRIVATE";
	private SharedPreferences prefsPrivate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.encrypted_string_view);
		tstring = (TextView) findViewById(R.id.oldString);
		outString = (TextView) findViewById(R.id.encryptedString);
		prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
		L = prefsPrivate.getString(KEY_PRIVATE, "Empty"); 
		tstring.setText(L);
		try {
			encrypt();
			outString.setText(Y);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

	public static String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;

		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10)
				strbuf.append("0");

			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}

		return strbuf.toString();
	}

	public void encrypt() throws Exception {

		String message = "This is just an example";

		// Get the KeyGenerator

		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128); // 192 and 256 bits may not be available

		// Generate the secret key specs.
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();

		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

		// Instantiate the cipher

		Cipher cipher = Cipher.getInstance("AES");

		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

		byte[] encrypted = cipher.doFinal(L.getBytes());
		// System.out.println("encrypted string: " + asHex(encrypted));
		Y = asHex(encrypted);

		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] original = cipher.doFinal(encrypted);
		String originalString = new String(original);
		// System.out.println("Original string: " + originalString + " "
		// + asHex(original));

	}

}
